package cn.org.timespace.easyframe.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>
 * 验证码
 * </p>
 *
 * @version 1.0, 11/01/18
 * @since 1.0
 * @author 
 */


public class EfAuthCodeAction extends ActionSupport {
	
	private static final long serialVersionUID = -1341400412702575722L;


	public String execute() throws Exception {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpServletResponse response = ServletActionContext.getResponse();
			
			String s = drawRandomCode(request,response);
			HttpSession session = request.getSession(true);
			session.setAttribute("validateCode", s);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	private String drawRandomCode(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
		
		BufferedImage img = new BufferedImage(68, 22,BufferedImage.TYPE_INT_RGB);
		Graphics g = img.getGraphics();       // 得到该图片的绘图对象
		g.setColor(new Color(200, 150, 255));
		g.fillRect(0, 0, 68, 22);             //填充整个图片的颜色

		// 向图片中输出数字和字母
		StringBuffer sb = new StringBuffer();
		
		char[] ch = "ABCDEFGHJKMNPQRSTUVWXYZ23456789".toCharArray();
		int index, len = ch.length;
		Random r = new Random();
		for (int i = 0; i < 4; i++) {
			index = r.nextInt(len);
			g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
			g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));            // 输出的字体和大小
			g.drawString("" + ch[index], (i * 15) + 3, 18);                       // 写什么数字，在图片的什么位置画
			sb.append(ch[index]);
		}

		ImageIO.write(img, "JPG", response.getOutputStream());
		return sb.toString();
	}
	

	
}
